package com.tao.utilslib.file;

import android.os.Build;
import android.os.Environment;

import androidx.annotation.RequiresApi;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Instant;
import java.util.ArrayList;

/**
 * Created by ${Tao} on 2017-11-1709.
 */

public class FileUtil {
    /**
     * Android 获取磁盘SD卡文件的母目录
     * 如果SD 卡存在  则获取SD卡的目录
     * 如果SD 卡不存在  则获取本地磁盘目录
     *
     * @return
     */
    public static String getDirectoryPath() {
        File sdDir;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取SD根目录
        } else {
            sdDir = Environment.getRootDirectory();
        }
        return sdDir.toString();
    }


    public static ArrayList<String> listFiles(String path) throws Exception {


        File file = new File(path);
        if (file.exists()) {
            ArrayList<String> list = new ArrayList<>();

            if (file.isDirectory() && file.exists()) {

                File[] files = file.listFiles();
                for (File f : files) {
                    if (f.exists()) {
                        listFiles(f.getAbsolutePath());
                    }
                }

            } else {

                if (file.exists())
                    list.add(file.getAbsolutePath());
            }
            return list;
        }
        return null;
    }


    /**
     * 复制单个文件
     *
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public static void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
//                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }

    }


    public static void deleteParintFile(File file, boolean deleteParent) {
        if (file != null && file.exists()) {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                if (files != null) {
                    for (File f : files) {
                        if (f.exists()) {
                            if (f.isDirectory()) {
                                deleteParintFile(f, deleteParent);
                            } else {
                                deleteChildFile(f);
                            }
                        }
                    }
                }
                if (deleteParent)
                    deleteChildFile(file);
            }
        } else {
            deleteChildFile(file);
        }

    }

    public static void deleteParintFile(File file) {
        deleteParintFile(file, false);
    }

    public static boolean ifNotExisCreateFiles(String path)  throws  Exception{
        File file = new File(path);
        if (!file.exists()) {
            if (!file.getParentFile().exists()) {
                boolean mkdirs = file.getParentFile().mkdirs();
                if (!mkdirs) return false;
            } else {
                if (!file.getParentFile().isDirectory()) {
                    return false;
                }
            }
            try {
                file.createNewFile();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    public static long getCreationTimeByAndroid(File file) {
        return file.lastModified();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static long getCreationTimeByJava(File file) {
        BasicFileAttributes attr = null;
        try {
            Path path = file.toPath();
            attr = Files.readAttributes(path, BasicFileAttributes.class);
            // 创建时间
            Instant instant = attr.creationTime().toInstant();
            return instant.toEpochMilli();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.err.println("");
        }
        long lastModified = file.lastModified();
        return lastModified;
    }

    public static void deleteChildFile(File file) {
        try {
            file.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean copyStream2File(InputStream open, String filePath) {
        File file = new File(filePath);
        try {
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            } else if (file.isDirectory()) {
                deleteParintFile(file, true);
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            streamWriter(open, new FileOutputStream(file));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private static void streamWriter(InputStream inputStream, OutputStream outputStream) throws Exception {
        try {
            byte[] buffer = new byte[1444];
            int byteread = 0;
            while ((byteread = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, byteread);
            }
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
